<?php

namespace App\Http\Middleware;

use App\Services\Core\Traits\Response;
use App\Services\Ext\Cache\TokenService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

class ChkFrontAuth
{
    use Response;

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $token = $request->header('token');
        if ($token) {

            $memberId = Crypt::decryptString($token);

            if (!(new TokenService())->chkToken($memberId, $token)) $this->fail('请重新登录');

            $request->attributes->add([
                'member_id' => Crypt::decryptString($request->header('token'))
            ]);
        }else{
            $this->fail('请登录');
        }

        return $next($request);
    }
}
